
/*
对于callback的普适性：
第一个参数是error，第二个参数是正确返回的数据
一般情况下，两者仅有一个有效
*/
let mysqlHelper = function(app){
    let mysqlConfig = app.get('mysql');
    let mysql = require('mysql');
    let pool  = mysql.createPool(mysqlConfig);
    this.pool = pool;
};

module.exports = mysqlHelper;

mysqlHelper.prototype.query = function(sqlString, values, callback){
    console.log('######' + sqlString + values + '######');
    if (values) {
        this.pool.query(sqlString, values, callback);
    } else {
        this.pool.query(sqlString, callback);
    }
};

//游客登录
mysqlHelper.prototype.guestLogin = function(callback)
{
    // mysqlHelper.prototype.guestLogin = function(callback) {
        let sql = "insert into userinfo () values ();";
        this.query(sql, null, function(err, results, fileds){
            if (err) {
                callback(err, results);
            } else {
                let userid = results['insertId'];

                //==================强制添加userid == id
                let temsql =" update userinfo set userid = ? where id = ?;";
                this.query(temsql, [userid, userid], function (err, results, fileds) {
                        if(err)
                        {
                            callback(err,results);
                        }else{
                            console.log("登录成功");

                        }
                });
                //====================
                this.queryguestInfo(userid, callback);
            }
        }.bind(this));
    // };
    // let userinfo = {};
    // let userid = '1';
    // for(let i=0; i<5; i++)
    // {
    //     userid += Math.floor(Math.random() * 10);
    // }
    // userinfo.userid = userid;
    // userinfo.gold = 300;
    // userinfo.roomcard = 100;
    // userinfo.diamond = 100;
    //
    // callback(null, userinfo);
};
//查询游客信息
mysqlHelper.prototype.queryguestInfo = function(userid, callback) {
    let sqlString = "select * from userinfo where id = ?";
    console.log('userid = ', userid);
    this.query(sqlString, [userid], function(err, results, fileds){
        if (results.length > 0) {
            results[0].userid = results[0].id;
            callback(err, results[0]);
        } else {
            callback("没有该用户", null);
        }
    });
};
//用户登录
mysqlHelper.prototype.userLogin = function(callback)
{
    let sqlString = "select * from userinfo where userid = ?";
    this.query(sqlString, [userid], function(err, results, fileds){
        if (results.length > 0) {
            callback(err, results[0]);
        } else {
            callback("没有该用户", null);
        }
    });
};

//查询用户信息
mysqlHelper.prototype.queryUserInfo = function(userid, callback) {
    let sqlString = "select * from userinfo where userid = ?";
    this.query(sqlString, [userid], function(err, results, fileds){
        if (results.length > 0) {
            callback(err, results[0]);
        } else {
            callback("没有该用户", null);
        }
    });
};


//事务入口
mysqlHelper.prototype.beginTransaction = function(callback) {
    this.pool.getConnection(callback);
};

//根据用户输赢更新数据库，并返回用户的金币总额
mysqlHelper.prototype.updateUsersGold = function(ugoldResults, callback){
    this.beginTransaction(function(err, connection) {
        if (err) {
            if (callback) {
                callback(err);   
            }
            return;
        }
        let userids = [];
        for (let index = 0; index < ugoldResults.length; index++) {
            let element = ugoldResults[index];
            let userid = element.userid;
            userids.push(userid);
            let getGold = element.getGold;
            let sqlString = "update userinfo set gold = IF(gold + '?' < 0, 0, gold + '?') where userid = ?;";
            connection.query(sqlString, [getGold, getGold, userid]);
        }

        let useridString = userids.join(',');
        let sqlString = "select userid, gold from userinfo where userid in(" + useridString + ");";
        console.log(sqlString);
        connection.query(sqlString, function(err, results, fileds) {
            if (!err) {
                for (let index = 0; index < ugoldResults.length; index++) {
                    let element = ugoldResults[index];
                    let dbElement = results[index];
                    element.totalGold = dbElement.gold;
                }
            }
        });
        connection.commit(function(err) {
            if (err) {
                connection.rollback();
                callback(err, ugoldResults);
            } else {
                if (callback) {
                    callback(null, ugoldResults);
                }
            }
        });
    });
};